<template>
  <div class="spl-container">
    <breadcrumb :data="pathData"></breadcrumb>
  <div style="padding: 0 20px;">
    <!-- //搜索框和添加用户框 -->
    <el-row type="flex" class="row-bg pt-20" justify="space-between">
      <div class="search-row">
        <el-input placeholder="搜索角色名称" clearable class="ml-20 w-220" v-model="roleName_like"></el-input>
        <el-button type="primary" class="search-btn" icon="el-icon-search" @click="getTableData"></el-button>
      </div>
      <div class="search-row-btn">
          <el-button type="primary" class="opt-btn" icon="el-icon-circle-plus-outline" @click="dialogFormVisible=true">添加角色</el-button>
      </div>
    </el-row>
    <!-- 角色权限tab部分 -->
    <dTable @fetch="getTableData" ref="empTable" :tableHeight="tableHeight">
        <el-table-column prop="roleCode" label="角色编码" header-align="center" min-width="130" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" header-align="center" align="left" min-width="130" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="description" label="角色描述" header-align="center" align="left" min-width="150" :show-overflow-tooltip="true">
        </el-table-column>
        <el-table-column prop="status" label="是否启用" header-align="center" align="center" min-width="130">
          <template slot-scope="scope">
            <!-- 角色状态:{00 生效，11 失效}-->
            <el-switch v-if="scope.row.type!='00'" v-model="scope.row.status" :activeColor="$global.switchColor[0]"
                       :inactiveColor="$global.switchColor[1]" @change="activeRole(scope.row)"
                       :active-value="'00'"
                       :inactive-value="'11'">
            </el-switch>
            <span v-if="scope.row.type=='00'"></span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" header-align="center" align="center">
          <template slot-scope="scope">
            <div class="table-operate-btns">
              <el-button type="text" icon="el-icon-circle-check" class="btn edit-btn" @click="rolePower(scope.row)">授权</el-button>
              <el-button type="text" icon="el-icon-set-up" class="btn edit-btn" @click="setInfo(scope.row)">分配</el-button>
            </div>
          </template>
        </el-table-column>
      </dTable>
    <!-- //新增用户的diag -->
    <el-dialog title="添加角色"  class="spl-dialog" :visible.sync="dialogFormVisible" width="600px" center>
      <el-form :model="ruleForm" ref="ruleForm" label-width="120px">
        <div class="add-ruleForm">
          <el-form-item label="角色编码" prop="roleCode" :rules="[{ required: true, message: '请输入角色编码', trigger: 'blur'},{validator:this.validRoleCode,trigger:'blur'}]">
            <el-input v-model="ruleForm.roleCode" placeholder="请输入" class="w-250"></el-input>
          </el-form-item>
          <el-form-item label="角色名称" prop="roleName" :rules="{ required: true, message: '请输入角色编码', trigger: 'blur' }">
            <el-input v-model="ruleForm.roleName" placeholder="请输入" class="w-250"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="description" class="mb-0">
            <el-input type="textarea" v-model="ruleForm.description" placeholder="请输入"
                      :autosize="{minRows: 2, maxRows: 5}"
            ></el-input>
          </el-form-item>
          <el-form-item style="margin-bottom: 10px;">
            <el-checkbox v-model="checked" @change="changeAddStatus">是否启用</el-checkbox>
          </el-form-item>

        </div>
      </el-form>
      <div slot="footer" class="dialog-footer operate-btns-bottom">
        <el-button @click="dialogFormVisible = false" class="mr-40">取 消</el-button>
        <el-button type="primary" :loading="addBtnLoading" @click="doSaveAdd">保 存</el-button>
      </div>
    </el-dialog>

    <!-- //抽屉组件的打开 -->
    <el-drawer title="角色授权" class="spl-drawer" :visible.sync="setPowerVisible" direction="rtl" size="450px" :wrapperClosable="false" :before-close="cancelSetRolePower">
      <div class="demo-drawer__content">
        <el-form :model="roleInfo" label-width="80px">
          <el-form-item label="角色名称:">
            <el-input v-model="roleInfo.roleName" :readonly="true" autocomplete="off" class="w-300"></el-input>
          </el-form-item>
          <p class="ml-10">分配权限:</p>
          <div class="pl-20">
            <el-card class="mt-10" shadow="hover" :style="{height: setTreeHeight}">
              <el-tree :data="setPowerTreeData" show-checkbox node-key="id" ref="resourceTree" :default-expand-all="true"
                       :default-checked-keys="checkResources" :props="defaultProps">
              </el-tree>
            </el-card>
          </div>
          <div class="operate-btns-bottom mt-30">
            <el-button class="white-btn" @click="cancelSetRolePower">取 消</el-button>
            <el-button type="primary" class="ml-30" @click="saveRoleResource('0')">保 存</el-button>
          </div>
        </el-form>
      </div>
    </el-drawer>

    <el-drawer title="角色编辑" class="spl-drawer" :visible.sync="roleEditDrawer" direction="rtl" size="550px" :wrapperClosable="false" :before-close="cancelRoleEdit">
      <div class="demo-drawer__content">
        <el-form :model="roleEditForm" label-width="80px">
          <el-form-item label="角色名称:">
            <el-input v-model="roleEditForm.name" :readonly="true" autocomplete="off" class="w-300"></el-input>
          </el-form-item>
          <p class="ml-10">分配用户:</p>
          <div class="pl-20 mt-10 pr-15">
            <el-row>
              <el-col :span="16">
                <div class="border-box-p10 border-r-none" :style="{height: roleEditHeight}" style="overflow: auto;">
                  <div class="filter-area m-form">
                    <!--<el-input placeholder="搜索部门或用户名称" v-model="filterText" class="w-280"></el-input>-->
                    <el-input placeholder="搜索部门" v-model="filterText" class="w-280"></el-input>
                  </div>
                  <!--<p class="allOrg" @click="getOrgUser()">全部</p>-->
                  <el-tree
                    class="filter-tree"
                    highlight-current
                    :data="orgTreeData"
                    :props="orgTreeProps"
                    default-expand-all
                    :filter-node-method="filterNode"
                    @node-click="nodeClick"
                    ref="orgTree">
                    <span slot-scope="{ node, data }" :class="data.icon!=null?'mt--10':''">
                      <i :class="data.icon==null?'el-icon-office-building':data.icon"></i>
                      <span style="padding-left: 4px;">{{node.label}}</span>
                    </span>
                  </el-tree>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="border-box-p10" :style="{height: roleEditHeight}" style="overflow: auto;">
                  <el-checkbox v-for="(item,index) in allUser" :key="$global.generate('check',10)" :ref="'user'+item.id" :checked="roleUserIds.indexOf(item.id)>=0" @change="changeCheckStaus($event,item,0)">{{item.userName}}</el-checkbox>
                </div>
              </el-col>
            </el-row>
            <div class="border-box-p10 border-t-none" style="overflow: auto;">
              <p>已选：<span class="text-blue" v-text="roleUserIds.length+'/'+totalUser"></span></p>
              <div class="mt-10" style="max-height: 380px;min-height: 100px;overflow-y: auto">
                <el-tag @close="changeCheckStaus(false,item,1)"
                  :key="item.id"
                  v-for="(item,index) in roleUsers"
                  closable type="info"
                  :disable-transitions="true" class="mr-10 mb-10">
                  {{item.userName}}
                </el-tag>
              </div>
            </div>
            <div class="operate-btns-bottom mt-30">
              <el-button class="white-btn" @click="cancelRoleEdit">取 消</el-button>
              <el-button type="primary" class="ml-30" :loading="roleEditBtnLoading" @click="saveRoleResource('1')">保 存</el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
  </div>
</template>
<script>
import dTable from '../../components/common/table'
export default {
  components: { dTable },
  data () {
    return {
      // 导航
      pathData: [
        { name: '企业管理' },
        { name: '角色权限' }
      ],
      roleName_like: '',
      checkResources: [],
      roleInfo:{},
      state: '',
      // 新增角色
      addBtnLoading: false,
      ruleForm: {
        description: '',
        roleCode: '',
        roleName: '',
        status: '00' //  <!-- 角色状态:{00 生效，11 失效}-->
      },
      checked: true, // 添加角色-是否启用
      dialogFormVisible: false,

      // 授权
      setPowerVisible: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      setPowerTreeData: [],
      defaultProps: {
        children: 'childResources',
        label: 'resourceName'
      },

      // 分配
      roleEditDrawer: false,
      roleEditBtnLoading: false,
      roleEditForm: {
        id: '',
        name: ''
      },
      filterText: '',
      orgTreeData: [],
      orgTreeProps: {
        children: 'subOrginization',
        label: 'name'
      },
      roleUsers: [],
      roleUserIds: [],
      allUser: [],
      totalUser: 0,
      orgId: ''
    }
  },
  watch: {
    filterText (val) {
      this.$refs.orgTree.filter(val)
    }
  },
  computed: {
    tableHeight: function () {
      return this.$global.bodyHeight - 200 + 'px'
    },
    setTreeHeight: function () {
      return this.$global.bodyHeight - 250 + 'px'
    },
    roleEditHeight: function () {
      return this.$global.bodyHeight - 600 + 'px'
    }
  },
  created () {
    this.$nextTick(() => {
      this.getTableData() // 获取列表数据
      this.getOrgTreeData() // 获取组织架构树数据

    })
  },
  methods: {
    getTableData () {
      var params = [{ property: 'roleName_like', value: this.roleName_like }]
      this.$refs.empTable.fetch(params, 'post', '/tenant/role/page')
    },
    // 新增角色--切换是否启用
    changeAddStatus (val) {
      // 角色状态:{00 生效，11 失效}
      if (val) {
        this.ruleForm.status = '00'
      } else {
        this.ruleForm.status = '11'
      }
    },
    validRoleCode (rule, value, callback){
      if (value != undefined && value != null && value != '') {
        this.$http({
          url: '/tenant/no-limit/validRoleCode',
          method: 'get',
          params: {
            roleCode: value
          }
        }).then(({data}) => {
          if (data.code == -1) {
            if (!data.data) {
              callback(new Error(data.msg))
            } else {
              callback()
            }
          } else {
            callback()
          }
        })
      }
    },
    //  新增角色--保存
    doSaveAdd () {
      this.$refs.ruleForm.validate((valid) => {
        this.addBtnLoading = true
        if (!valid) {
          this.addBtnLoading = false
        } else {
          this.$http({
            url: '/tenant/role/save',
            method: 'post',
            data: this.ruleForm
          }).then(({ data }) => {
            this.addBtnLoading = false
            if (data.code == 0) {
              this.dialogFormVisible = false
              this.getTableData()
              this.$message.success('保存成功')
              this.clearAddDialog()
            } else {
              if (data.msg) {
                this.$message.error(data.msg)
              } else {
                this.$message.error(this.$global.errorMsg)
              }
            }
          })
        }
      })
    },
    activeRole (role){
        this.$http({
          url: '/tenant/role/status/change',
          method: 'put',
          data: {
            roleId: role.id,
            status: role.status
          }
        }).then(({data}) => {
          if(data.code !==0) {
              this.$message.error(data.msg)
          }
          this.getTableData()
        })
    },

    // 新增角色--清除数据
    clearAddDialog () {
      this.ruleForm.description = ''
      this.ruleForm.roleCode = ''
      this.ruleForm.roleName = ''
      this.ruleForm.status = '00'
      this.$refs.ruleForm.clearValidate()
    },

    // 授权
    rolePower (row) {
      this.getResourcesByRole(row)
      this.roleInfo = row
      this.setPowerVisible = true
    },

    saveRoleResource (type){
      this.$http({
        url: '/tenant/role/authorize',
        method: 'put',
        data: {
          authorizeIds: type == '0' ? this.$refs.resourceTree.getCheckedKeys(false) : this.roleUserIds,
          id: type == '0' ? this.roleInfo.id : this.roleEditForm.id,
          type: type
        }
      }).then(({data}) => {
          if(type === '0'){
            this.cancelSetRolePower()
          }else{
            this.cancelRoleEdit()
          }
      })
    },
    cancelSetRolePower(done){
      this.checkResources = []
      this.roleInfo = {}
      if(typeof done === 'function'){
        done()
      }else{
        this.setPowerVisible = false
      }
    },
    setInfo (row) {
      this.roleEditForm.id = row.id
      this.roleEditForm.name = row.roleName
      this.getOrgUser(this.orgId,1)//获取组织架构用户
      this.roleEditDrawer = true
    },
    getResourcesByRole(row){
      this.checkResources = []
      this.$http({
        url: 'tenant/getResourcesByRole/'+row.id,
        method: '',
        params: {}
      }).then(({data}) => {
        if(data.code == 0){
          this.setPowerTreeData = data.data
          this.getCheckResources(data.data)
        }
      })
    },
    getCheckResources(resources){
      resources.forEach(item => {
        if(item.exist){
          this.checkResources.push(item.id)
        }
        if(item.childResources!=undefined && item.childResources instanceof Array){
            this.getCheckResources(item.childResources)
        }
      })
    },
    //  分配
    // 获取组织架构树数据
    getOrgTreeData (moduleCode) {
      this.$http({
        url: '/company/organization/tree',
        method: 'get',
        param: {}
      }).then(({ data }) => {
        if (data.code === 0) {
          var all = [{id: '',name:'所有部门',icon: 'el-icon-s-home'}]
          var allOrg = all.concat(data.data.subOrginization)
          this.orgTreeData = allOrg
        }
      })
    },
    getOrgUser (orgId,type){
      var that = this
      this.$http({
        url: '/company/getOrgnizeUser',
        method: 'get',
        params: {orgnizeId: orgId,roleId: this.roleEditForm.id}
      }).then(({data}) => {
        if(data.code==0){
          that.allUser = data.data
          if(type!=undefined){
            that.totalUser = data.data.length
            that.roleUsers = []
            that.roleUserIds = []
            data.data.forEach(item => {
                if(item.existPower){
                  that.roleUsers.push(item)
                  that.roleUserIds.push(item.id)
                }
            })
          }
        }
      })
    },
    changeCheckStaus(value,user,type){
      if(value){
        this.roleUsers.push({id:user.id,userName:user.userName})
        this.roleUserIds.push(user.id)
      }else{
        var index = this.roleUserIds.indexOf(user.id)
        this.roleUsers.splice(index,1)
        this.roleUserIds.splice(index,1)
        if(type == 1){
          this.getOrgUser(this.orgId)
        }
      }
    },
    cancelRoleEdit(done){
      this.allUser = []
      this.roleUsers = []
      this.roleUserIds= []
      this.orgId = ''
      this.filterText = ''
      this.roleEditForm ={
        id: '',
        name: ''
      }
      if(typeof done === 'function'){
          done()
      }else{
          this.roleEditDrawer = false
      }
    },
    //  点击节点，获取节点信息
    nodeClick (data, node, ele) {
      this.orgId = data.id
      this.getOrgUser(data.id)
    },
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    }
  }

}
</script>
<style lang="less" scoped>
  .add-ruleForm{
    padding-right: 30px;
  }
  .allOrg{
    margin-top: 10px;
    padding-left: 22px;
    height: 26px;
    line-height: 26px;
  }
  .allOrg:hover{
    background-color: #F5F7FA;
  }
  .mt--10 {
    margin-left: -10px;
  }
</style>
